import { EditorState, convertToRaw, ContentState } from 'draft-js';
import React, { PureComponent } from 'react';
import { Editor } from 'react-draft-wysiwyg';
import QiniuUploader from '../../utils/qiniu';
import '../../../node_modules/react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';

export default class MyEditor extends PureComponent{
  state = {
    editorState: EditorState.createEmpty(),
  };

  componentWillReceiveProps = ( props )=>{
     if(props.content){
       const editorState = EditorState.createWithContent(ContentState.createFromBlockArray(htmlToDraft(props.content)));
       this.setState({
         editorState,
       });
     }
  };

  onEditorStateChange = (editorState)=>{
    this.props.onChange(draftToHtml(convertToRaw(editorState.getCurrentContent())));
    this.setState({
      editorState,
    });
  };

  bindEditorUploadImage = (file)=>{
    console.log(file);
    return new Promise(
      (resolve, reject) => {
        QiniuUploader({
          file : file,
          success : (url)=>{
            resolve({data:{link:url}});
          },
          error : (err)=>{
            reject(err);
          }
        });
      }
    );
  };

  render(){
    const { editorState } = this.state;

    return <Editor
      editorClassName="home-editor"
      editorState={editorState}
      onEditorStateChange={this.onEditorStateChange}
      toolbar={{
        image: {
          previewImage: true,
          uploadCallback: this.bindEditorUploadImage,
          alt: { present: false, mandatory: false }
        },
      }}
    />
  }
}
